Python Programming Lab · Exp-6

Understanding Functions in Python

A definitive guide to standard functions, recursion, decorators, arguments and lambda expressions.

🧱 Custom Built 🔁 Recursion ⚡ Lambdas

Use ← → keys or swipe to navigate

Session Overview

What We Cover Today

01

Function Basics

Defining tools, tracking mins/maxs, and math logic.

02

Recursion

Eliminating loops to build Fibonacci trees.

03

Lambda Functions

One-line anonymous architectures.

04

Arguments

Keyword, default, and variable length parsing.

Problem 1

Max and Min Without Built-Ins

Task: Find the maximum and minimum numbers from a sequence without using the max() or min() functions.

def find_max_min(sequence):
    # Base case validation
    if not sequence:
        return None, None
        
    max_num = sequence[0]
    min_num = sequence[0]
    
    for num in sequence[1:]:
        if num > max_num:
            max_num = num
        if num < min_num:
            min_num = num
            
    return max_num, min_num

# Usage:
m_max, m_min = find_max_min([10, 6, 8, 90, 12, 56])
print(f"Max: {m_max}, Min: {m_min}")
Problem 2

Sum of Cubes Below N

Task: Create a function taking an integer and returning the sum of the cubes of all positive integers strictly smaller than it.

def sum_of_cubes(n):
    total = 0
    # Loop dynamically handles bounds from 1 up to (n-1)
    for i in range(1, n):
        total += (i ** 3)
        
    return total

# Alternative Pythonic 1-Liner using generator expression
def sum_of_cubes_fast(n):
    return sum(i ** 3 for i in range(1, n))

print(sum_of_cubes(4))  # (1^3) + (2^3) + (3^3) = 1 + 8 + 27 = 36
Recursion
Function calls itself

Moving away from iteration. We can solve problems recursively by shrinking the problem payload each time a function calls itself until it hits the base case.

Problem 3

Print 1 to N Using Recursion

Task: Emulate a loop, printing 1 up to N using a recursive function (no FOR or WHILE statements).

def print_1_to_n(n):
    # 1. Base statement checks when to break out
    if n > 0:
        # 2. Call the function with progressively smaller number limit
        print_1_to_n(n - 1)
        
        # 3. Operations resolve from bottom to top upon function return
        print(n, end=" ")

# Output will be: 1 2 3 4 5  
print_1_to_n(5) 

🧠 The Call Stack

If the print statement was placed before the recursive call, the output would be reversed (`5 4 3 2 1`). By placing it after, the function resolves sequentially starting from the deepest base case calculation.

Problem 4

Fibonacci Sequence with Recursion

Task: Recursively output the Fibonacci series up to `N` terms directly mapped through function parameters.

def recursive_fib(n, a=0, b=1):
    # Break execution lock if N term countdown bottoms out
    if n > 0:
        print(a, end=" ")
        # n-1 decreases term counter.
        # The next 'a' becomes the current 'b'.
        # The next 'b' becomes 'a + b'.
        recursive_fib(n-1, b, a+b)

recursive_fib(7)
# Process: 0 1 1 2 3 5 8
λ Lambda
Anonymous Operations

A lambda function is a small autonomous function that can evaluate a single expression and return the output without needing a formal `def` block wrapper.

Problem 5 & 6

Implementing Lambdas

Task: Write one-line lambdas to a) Calculate Cone volume and b) Give a Tuple of Max/Min points from a List.

import math

# Volume of Cone ( V = 1/3 * π * r² * h )
vol_cone = lambda r, h: (1/3) * math.pi * (r**2) * h

print(f"Volume: {vol_cone(5, 10):.2f}")


# Tuple mapped extraction
min_max_tuple = lambda lst: (max(lst), min(lst))

data = [10, 6, 8, 90, 12, 56]
print("Result:", min_max_tuple(data))
  • Lambdas act as anonymous single-expression formulas.
  • Use format: lambda arguments : expression
Problem 7

Function Arguments

Explaining Keyword `kwargs`, Default arguments, and Variable Length sequences `*args`.

# A. Keyword Arguments (Order doesn't matter)
def greet(first_name, last_name):
    print(f"Welcome {first_name} {last_name}")

greet(last_name="Dar", first_name="Mohsin")


# B. Default Arguments (Fallback if no arg passed)
def calculate_tax(price, rate=0.18):
    return price + (price * rate)

print(calculate_tax(1000))       # Output 1180.0


# C. Variable Length arguments (Indefinite tuples via *args)
def add_multiple(*args):
    return sum(args)

print(add_multiple(5, 10, 15, 20)) # Can take limitless parameters
Problem 8

Checking Identical Dictionary Values

Task: Check whether all the values in a dictionary are identical using a lambda function.

# A dictionary's .values() method yields the array map of data.
# A python Set automatically removes all duplicated inputs.
# Ergo, if the length of the Set is 1, all values are identical.

check_identical = lambda d: len(set(d.values())) == 1 if d else True

dict1 = {'a': 10, 'b': 10, 'c': 10}
dict2 = {'a': 10, 'b': 20, 'c': 10}

print("Dict 1 identical:", check_identical(dict1))  # True
print("Dict 2 identical:", check_identical(dict2))  # False
Problem 9

List to Dictionary Merger

Task: Create two lists and generate a dictionary with keys exclusively from list1 and values heavily reliant from list2.

list1 = ["Name", "Age", "City"]
list2 = ["Mohsin", 32, "Dehradun"]

# Method A: Using a Zip sequence wrapper
merged_dict = dict(zip(list1, list2))

print("A) Zip Method :", merged_dict)


# Method B: Using Iterative Append
manual_dict = {}
for i in range(len(list1)):
    manual_dict[ list1[i] ] = list2[i]

print("B) Loop Method:", manual_dict)
Use arrow keys or swipe to navigate